/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.service;

import br.com.foxline.enums.Status;
import br.com.foxline.model.Message;
import br.com.foxline.model.Reserve;
import br.com.foxline.model.Users;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Schedules;
import javax.ejb.Stateless;
import javax.ejb.TimerService;
import javax.persistence.Query;

/**
 *
 * @author luciano
 */
@Stateless
public class ReserveService extends GenericService<Reserve> {

    @EJB
    private LotService lotService;
    
    @EJB
    private ManagerReservaBean managerReservaBean;
    
    @EJB
    private MessageService messageService;
    
    public ReserveService() {
        super(Reserve.class);
    }

    @Override
    public void save(Reserve reserve) {
        reserve.setCreatedAt(new Date());
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, 1);
        reserve.setExpiresAt(c.getTime());
        managerReservaBean.startTimer(reserve);
        super.save(reserve);
    }

    public void expireReserve(){
        String sql = "select r from Reserve r where r.expiresAt < CURRENT_TIMESTAMP and r.lot.status=:status";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("status", Status.RESERVADO);
        List<Reserve> reserves =  query.getResultList();
        for (Reserve reserve : reserves) {
            reserve.getLot().setStatus(Status.DISPONIVEL);
            lotService.save(reserve.getLot());
            reserve.setExpired(true);
            super.save(reserve);
            Users u = new Users();
            u.setId(new Long(1)); 
            String message = "Sua reserva do Lote:" + reserve.getLot().getNum() + ", Quadra: " + reserve.getLot().getBlock() + ", no Empreendimento: " + reserve.getLot().getEnterprise().getName() + " expirou hoje, e agora o lote encontra-se disponível para venda.";
            Message m = new Message(u, reserve.getReserverCorrector().getUser(),"Reserva expirou" , message, null, false);
            messageService.save(m);
        }
        
    }
    
    public List<Reserve> getMyReserve(Users user){
        String sql = "select r from Reserve r where r.responsibleUsers=:user order by r.expiresAt desc";
        Query query = getEntityManager().createQuery(sql);
        query.setParameter("user", user);
        return query.getResultList();

    }
    
    
}
